package com.freemyleft.left.zapp.net.download;

/**
 * Created by FreeMyleft on 2017/12/3.
 */

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;

import com.freemyleft.left.zapp.app.Left;
import com.freemyleft.left.zapp.net.callback.IRequest;
import com.freemyleft.left.zapp.net.callback.ISuccess;
import com.freemyleft.left.zapp.util.FileUtil;

import java.io.File;
import java.io.InputStream;

import okhttp3.ResponseBody;

/**
 *异步加载
 */
public class SaveFileTask extends AsyncTask<Object,Void,File>{
    private final IRequest REQUEST;
    private final ISuccess SUCCESS;

    public SaveFileTask(IRequest REQUEST, ISuccess SUCCESS) {
        this.REQUEST = REQUEST;
        this.SUCCESS = SUCCESS;
    }

    @Override
    protected File doInBackground(Object... params) {
        String downloadDir= (String) params[0];//默认第一个参数
        String extension= (String) params[1];
        final ResponseBody body= (ResponseBody) params[2];
        final String  name= (String) params[3];
        final InputStream is=body.byteStream();
        //如果download为空或者是一个空的字符串
        if (downloadDir==null||downloadDir.equals("")){
            downloadDir="down_loads";
        }
        if (extension==null||extension.equals("")){
            extension="";
        }
        // TODO: 2017/12/3 文件名为空的话
        if (name==null){
            //写入磁盘的名字 参数输入流 文件目录 文件名通过后缀名改大写 后缀名
            return FileUtil.writeToDisk(is,downloadDir,extension.toUpperCase(),extension);

        }else {
            return FileUtil.writeToDisk(is,downloadDir,name);

        }

    }

    @Override
    protected void onPostExecute(File file) {
        super.onPostExecute(file);
        if (SUCCESS!=null){
            SUCCESS.onSuccess(file.getPath());
        }
        if (REQUEST!=null){
            REQUEST.onRequestEnd();
        }
        autoInstallApk(file);
    }

    /**
     * 自动安装APk文件
     * @param file 文件
     */
    private void autoInstallApk(File file){
        // TODO: 2017/12/3 getExtension 取出后缀名
        if (FileUtil.getExtension(file.getPath()).equals("apk")){
            final Intent install=new Intent();
            install.setAction(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            Left.getApplicationContext().startActivity(install);

        }
    }
}
